import router from '@/router';
import { pinia } from '@/store';
import { useKeepAliveStore } from '@/store/keep-alive';
import { isEmpty } from '@/utils/index';
import { toRawType } from '@/utils/validate';

const keepAliveStore = useKeepAliveStore(pinia);

/**
 * @description: 校验传入值是否是字符串类型
 * @param {any} val
 */
const isString = (val: any) => toRawType(val) === 'String';

const getCurrentRoute = () => router.currentRoute.value;

/**
 * 路由重定向
 * @param route {string|route} 需要刷新的路由，不传时为当前路由，如果是字符串时请确保以'/'开头
 * @param replace {boolean}    是否使用replace进行跳转
 * @return                     返回vue-router跳转的结果
 */
export const redirectPage = (routeInfo: any = getCurrentRoute(), replace = true): any => {
  const target = `/redirect${isString(routeInfo) ? routeInfo : routeInfo.fullPath}`;
  return router[replace ? 'replace' : 'push'](target);
};

/**
 * @description: 刷新页面并清除缓存
 * @param route {string|route} 需要刷新的路由，不传时为当前路由，如果是字符串时请确保以'/'开头
 * @param replace {boolean}    是否使用replace进行跳转
 * @return                     返回vue-router跳转的结果
 */
export const refreshPage = (routeInfo: any = getCurrentRoute(), replace = true): any => {
  keepAliveStore.deleteCacheOnly(routeInfo); // 清除缓存
  redirectPage(routeInfo, replace);
};

/**
 * @description: 关闭当前页签
 * @param next 跳转的目标页面，作为第一个参数传入vue-router.replace
 * @return 仅在next有值时，返回vue-router.replace的结果
 */
export const closeCurrentPage = (next = ''): any => {
  keepAliveStore.deleteTagAndCache(getCurrentRoute());
  if (!isEmpty(next)) {
    router.replace(next);
  }
};

/**
 * @description: 关闭指定页签（默认关闭当前页）
 * @param next 跳转的目标页面，作为第一个参数传入vue-router.replace
 * @return 仅在next有值时，返回vue-router.replace的结果
 */
export const closePage = (routeInfo: any = getCurrentRoute(), next = ''): any => {
  keepAliveStore.deleteTagAndCache(routeInfo);
  if (!isEmpty(next)) {
    router.replace(next);
  }
};
